#!/usr/bin/env python
#coding=utf-8


import datetime
import pandas as pd
from app.bill.models.bill_instance import BillInstance
from app.bill.models.bill_analysis import BillAnalysis
from app.bill.models.tag_department import TagDepartment
from core.logger import logger
from sqlalchemy.orm import Session


class TagDepartmentUtils(object):
    def __init__(self, ):
        self.department = {
            "运维": {"maintain_department": "运维", "belong_department": "运维"},
            "运维_人工智能": {"maintain_department": "运维", "belong_department": "人工智能"},
            "运维_管理系统": {"maintain_department": "运维", "belong_department": "管理系统"},
            "运维_数据智能": {"maintain_department": "运维", "belong_department": "数据智能"},
            "运维_天冕智能": {"maintain_department": "运维", "belong_department": "天冕科技"},
            "运维_虚拟银行": {"maintain_department": "运维", "belong_department": "虚拟银行项目组"},
            "运维_公共资源": {"maintain_department": "运维", "belong_department": "公共资源"},
            "数据库": {"maintain_department": "数据库", "belong_department": "数据库"},
            "大数据": {"maintain_department": "大数据", "belong_department": "大数据"},
            "信息安全": {"maintain_department": "信息安全", "belong_department": "信息安全"},
        }


    def get_department_by_product_name(self, bill):
        """
        根据产品类型，获取项目名称
        """

        data = {
            "云解析DNS": self.department["运维_公共资源"],
            "共享带宽": self.department["运维_公共资源"],
            "短信服务": self.department["运维_公共资源"],
            "全站加速": self.department["运维_公共资源"],
            "云监控": self.department["运维_公共资源"],
            "NAS": self.department["运维_公共资源"],
            "VPN网关": self.department["运维_公共资源"],
            "NAT网关": self.department["运维_公共资源"],
            "CDN": self.department["运维_公共资源"],
            "共享流量包": self.department["运维_公共资源"],
            "对象存储": self.department["运维_公共资源"],
            "域名": self.department["运维_公共资源"],
            "数字证书管理服务": self.department["运维_公共资源"],
            "数据库备份": self.department["数据库"],
            "数据传输": self.department["数据库"],
            "数据库": self.department["数据库"],
            "无影云桌面": self.department["数据库"],
            "检索分析服务": self.department["数据库"],
            "大数据": self.department["大数据"],
            "智能语音": self.department["运维_人工智能"],
            "Web应用防火墙": self.department["信息安全"],
            "云防火墙": self.department["信息安全"],
            "DDoS防护": self.department["信息安全"],
            "态势感知": self.department["信息安全"],
            "加密服务": self.department["运维_管理系统"],
            "日志服务": self.department["信息安全"],
        }
        for product_names, department_info in data.items():
            if product_names in bill["product_name"]:
                    return department_info

        # 镜像
        if bill["product_name"] == "块存储" and bill["product_code"] == "snapshot":
            return self.department["运维_公共资源"]

        return False



    def get_department_by_instance_name(self, bill):
        """
        根据实例名称，获取部门名称
        """
        data = {
            "yunwei": self.department["运维"],
            "ops": self.department["运维"],
            "worker": self.department["大数据"],
            "data": self.department["数据库"],
            "sz": self.department["数据库"],
        }

        for name, department_info in data.items():
            if bill["instance_name"].startswith(name):
                    return department_info

        return False



    def get_department_by_account(self, bill):
        """
        根据账号名称，获取部门名称
        """
        data = {
            "tianmianlab": self.department["运维_数据智能"],
            "welabfintech": self.department["运维_天冕智能"],
            "welabbank": self.department["运维_虚拟银行"],
        }
        for account, department_info in data.items():
            if bill["account_name"] == account:
                return department_info

        return False



    def get_department_info_by_other(self, bill):
        """
        获取部门信息
        """
        # 根据实例名称开头
        department_info = self.get_department_by_instance_name(bill)

        # 根据产品
        if not department_info:
            department_info = self.get_department_by_product_name(bill)

        # 根据账号
        if not department_info:
            department_info = self.get_department_by_account(bill)


        if not department_info:
            department = {
                "environment": "生产环境",
                "maintain_department": "运维",
                "belong_department": {"公共资源": 100}
            }

            return department

        department = {
            "environment": "生产环境",
            "maintain_department": department_info["maintain_department"],
            "belong_department": {department_info["belong_department"]: 100}
        }
        return department



    def get_tag_value(self, bill, tag_key):
        """
        根据标签key获取标签值
        """
        if not bill["instance_tag"]:
            # 有些产品没有标签
            return "common"
        
        if bill["cloud_platform"] == "阿里云":
            for tmp_tag in bill["instance_tag"].split(";"):
                if f"key:{tag_key}" in tmp_tag:
                    value = tmp_tag.strip().split(" ")[1].split("value:")[1]
                    return value.strip()
            
        
        if bill["cloud_platform"] == "华为云":
            for tmp_tag in bill["instance_tag"].split(";"):
                if tag_key in tmp_tag:
                    value = tmp_tag.strip().split(f"{tag_key}:")[1]
                    return value.strip()
        
        # 可以打标签的，但是没有打
        logger.warning(f"instance_id:{bill['instance_id']} has no {tag_key} label")
        return "common"


    def get_department_info_by_tag(self, db: Session, bill: dict):
        tag_key = "appname"
        tag_value = self.get_tag_value(bill, tag_key)
        if tag_value == "common":
            # logger.warning(f"instance_id:{bill['instance_id']} has no {tag_key} label")
            return False

        tag_object = TagDepartment.get_object_by_tag(db, tag_key, tag_value)
        if not tag_object:
            logger.warning(f"tag {tag_key}:{tag_value} not in database")
            return False

        tag_info = TagDepartment.get_object_info_by_tag(db, tag_key, tag_value)
        department_info = {
            "environment": tag_info["environment"],
            "maintain_department": tag_info["maintain_department"],
            "belong_department": tag_info["belong_department"]
        }
        return department_info



    def get_department_info(self, db: Session, bill: dict):
        department_info = self.get_department_info_by_tag(db, bill)
        if department_info:
            return department_info

        department_info = self.get_department_info_by_other(bill)
        return department_info




    def get_company_name(self, db: Session, bill: dict):
        """
        获取公司名称
        """
        # 根据账号
        account = {
            "卫盈联": [
                "sa",
                "welabconsfin",
                "welabfintech",
                "welabcloud"
            ],
            "天冕": [
                "welabbank",
                "tianmianlab",
                "tianmiantech"
            ]
        }
        # 根据账号名称获取公司名称
        for company_name, account_names in account.items():
            if bill["account_name"] in account_names:
                return company_name


        department = {
            "天冕": [
                "数据智能",
                "人工智能",
                "信息安全",
            ]
        }
        # 根据归属部门来获取公司名称
        if bill["account_name"] == "tianmian":
            department_info = self.get_department_info(db, bill)
            if department_info["maintain_department"] == "大数据":
                return "卫盈联"

            for company_name, department_names in department.items():
                for belong_department, proportion in department_info["belong_department"].items():
                    if belong_department in department_names:
                        return company_name

            return "卫盈联"



    def get_classes_name_for_yunwei(self, db: Session, bill: dict, tag_value:str, department_info:dict):
        # 根据产品来归类
        product_classes = {
            "网络": ["虚拟专用网络", "虚拟私有云","负载均衡","弹性公网IP","转发路由器", "云企业网", "CDN", "云解析", "共享带宽", "全站加速", "VPN网关", "NAT网关", "共享流量包", "域名", "数字证书"],
            "基础服务": ["云监控", "短信服务", "消息通知服务", "日志服务"],
            "中间件": ["微服务引擎"],
            "存储": ["NAS", "对象存储", "文件存储"]
        }
        for classe, product_names in product_classes.items():
            for product_name in product_names:
                if product_name in bill["product_name"]:
                    return classe
        
        # 根据标签来归类, 先做一部分，将运维部门的产品归类出去，后续所有的标签都有归类属性再优化
        if tag_value != "common":
            tag_info = TagDepartment.get_object_info_by_tag(db, "appname", tag_value)
            if tag_info and tag_info["bill_class"]:
                return tag_info["bill_class"]
            
        # 可以划出去的资产，并且是属于独立的部门，则归类其他部门
        belong_department = list(department_info['belong_department'].keys())
        if len(belong_department) == 1:
            if belong_department[0] == "公共资源":
                return "公共资源"
            return f"{belong_department[0]}部门"
            
        return "运维部门"
        
        


    def get_classes_name(self, db: Session, bill: dict):
        tag_value = self.get_tag_value(bill, "appname")

        # # 大数据集群
        # if tag_value == "p_大数据离线集群":
        #     return "大数据离线集群"
        # if tag_value == "p_大数据实时集群":
        #     return "大数据实时集群"

        # 生产k8s集群
        if "p_k8s" in tag_value:
            return f"生产k8s集群"
        
        # 数据库集群
        department_info = self.get_department_info(db, bill)
        if department_info["maintain_department"] == "数据库": 
            return f"数据库集群"
        
        # 大数据集群
        if department_info["maintain_department"] == "大数据": 
            return f"大数据集群"
        
        # 测试环境
        if tag_value.startswith("i_"):
            return "测试环境"
        
        # 运维管理的资产进一步分类
        if department_info['maintain_department'] == "运维":
            return self.get_classes_name_for_yunwei(db, bill, tag_value, department_info)
        

        return f"{department_info['maintain_department']}部门"





def main():
    bill = {
        "instance_tag": "key:owner value:welab; key:group value:p_wedefend, p_AI"
    }
    # department = Department()
    # project_name = department.get_project_name(bill)
    # print(project_name)



if __name__ == "__main__":
    main()